import { FormInstance } from "ant-design-vue";
import { ref, nextTick, reactive, computed } from "vue";
import { IAdaptiveSearchFormProps } from "./types";
import { find } from "lodash-es";

export const useSearchForm = (props: IAdaptiveSearchFormProps) => {
  const formInstance = ref<FormInstance | null | any>();
  const formState = reactive<any>({ ...props.initialValues });

  const visibleItems = computed(() => {
    return props.items.filter((item) => !item.hidden);
  });

  const initFormRef = async (formRef: FormInstance | null) => {
    await nextTick();
    formInstance.value = formRef;
  };

  const getFormInstance = async () => {
    await nextTick();
    return formInstance.value;
  };

  const getField = (name, handler) => {
    const field = find(visibleItems.value, { name });
    if (handler && typeof handler === "function") return handler(field);
    return field;
  };

  const resetForm = () => {
    formInstance.value?.resetFields();
  };
  const clearFields = (name, value) => {
    if (Array.isArray(name) && name.length > 0) {
      name.forEach((item) => {
        formState[item] = value ?? undefined;
      });
      return;
    }
    formState[name] = value ?? undefined;
  };

  return {
    initFormRef,
    formState,
    clearFields,
    resetForm,
    getField,
    visibleItems,
    getFormInstance
  };
};
